package com.wchat.serviceimpl;

import com.wchat.dataobject.UserEntity;
import com.wchat.dataobject.VerifyCodeEntity;
import com.wchat.enums.ResultEnum;
import com.wchat.exceptions.ServiceException;
import com.wchat.repository.UserRepository;
import com.wchat.repository.VerifyCodeRepository;
import com.wchat.service.SendVerifyCode;
import com.wchat.utils.HttpUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

import java.util.Date;

@Service
public class SendVerifyCodeImpl implements SendVerifyCode {


    @Autowired private VerifyCodeRepository verifyCodeRepository;

    @Autowired private UserRepository userRepository;

    /**
     * 发送验证码
     * @param phoneNumber 手机号
     * @param avaliableTime 过期时间
     */
    @Override
    public void sendVerifyCodeAndSave(String phoneNumber, Integer avaliableTime) {

        UserEntity user = new UserEntity();
        //校验是否已经线下实名认证
        user = userRepository.findByPhoneNumber(phoneNumber);
        if(user != null && user.getIsNew() == 1){
            throw new ServiceException(ResultEnum.NO_VERIFIED.getCode(),ResultEnum.NO_VERIFIED.getValue());
        }
        int code = Integer.parseInt(generateVerifyCode()); // 动态声明验证码
        String tkey = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        HttpUtil.UrlBuilder builder = new HttpUtil.UrlBuilder(TEXT_URL);
        builder.setParam("username", TEXT_USERNAME);
        builder.setParam("mobile", phoneNumber);
        builder.setParam("tkey", tkey);
        builder.setParam("password", DigestUtils.md5Hex(DigestUtils.md5Hex(TEXT_PWD) + tkey));
        builder.setParam("content", String.format(TEXT_CONTENT, code));
        String url = builder.build();
        try {
            String res = HttpUtil.get(url);
            System.out.println("textres: " + res);
            if (res.indexOf("1,") == 0) {
                saveCode(phoneNumber, code, avaliableTime);
                return;
            }
            throw new ServiceException(ResultEnum.SENDVERIFYCODE_ERROR.getCode(),ResultEnum.SENDVERIFYCODE_ERROR.getValue());
        } catch (Exception e) {
            throw new ServiceException(ResultEnum.SENDVERIFYCODE_ERROR.getCode(),ResultEnum.SENDVERIFYCODE_ERROR.getValue());
        }

    }

    @Override
    public boolean checkoutVerifyCode(String phoneNumber, Integer code) {
        if(StringUtils.isBlank(String.valueOf(code)) || code == null){
            throw new ServiceException(ResultEnum.PHONENUMBER_IS_NO_VEROFICODE.getCode(),ResultEnum.PHONENUMBER_IS_NO_VEROFICODE.getValue());
        }
        VerifyCodeEntity verifyCodeEntity = verifyCodeRepository.findByPhoneNumber(phoneNumber);
        if(verifyCodeEntity == null){
            return false;
        } else if(verifyCodeEntity.getPhoneNumber().equals(phoneNumber) && code.equals(verifyCodeEntity.getVerifyCode()) && verifyCodeEntity.getIsUsed()==0){
          return true;
        }
        return false;
    }

    /**
     * 保存验证码并更新
     * @param phoneNumber
     * @param code
     * @param avaliableTime
     */
    private void saveCode(String phoneNumber, int code, Integer avaliableTime) {
        VerifyCodeEntity instance = verifyCodeRepository.findByPhoneNumber(phoneNumber);
        if(instance == null){
            VerifyCodeEntity verifyCodeEntity = new VerifyCodeEntity();
            verifyCodeEntity.setPhoneNumber(phoneNumber);
            verifyCodeEntity.setVerifyCode(code);
            verifyCodeEntity.setSendTime(new Date());
            verifyCodeRepository.save(verifyCodeEntity);
        }
        verifyCodeRepository.updateVerifyCodeByPhoneNumber(code,phoneNumber);
    }

    /**sim
     *  动态声明验证码
     * @return
     */
    private String generateVerifyCode() {
        return String.format("%06d", (int) Math.floor(Math.random() * 1000000));
    }

}
